package com.chenjt.netty.six_gPRC.simple;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * gRPC服务端
 *
 * 参考D:\programmer\studyWorkspace\netty\doc\grpc-java\examples\src\main\java\io\grpc\examples\helloworld\HelloWorldServer.java
 *
 * @author chenjt
 * @date 2024/8/16 10:29
 */
public class GrpcServer {

    private Server server;

    private void start() throws IOException {
        this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start();

        System.out.println("server started!");

        // 这里是异步的
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("关闭jvm");
            // jvm退出之前调用grpc的stop方法
            GrpcServer.this.stop();
        }));
        System.out.println("执行到这里");
    }

    private void stop(){
        if(null != this.server){
            this.server.shutdown();
        }
    }

    // 和thrift不一样，启动之后不会被阻塞住，这里得把它阻塞住
    private void awaitTermination() throws InterruptedException {
        if(null != this.server){
            this.server.awaitTermination();
            // 等待3秒，3秒后自动退出，会触发 Runtime.getRuntime().addShutdownHook
            // Process finished with exit code 0  0是正常退出
//            this.server.awaitTermination(3, TimeUnit.SECONDS);
        }
    }

    public static void main(String[] args) throws Exception {
        GrpcServer server = new GrpcServer();

        server.start();
        server.awaitTermination();
    }

}
